package com.beta.pay.yeepay.core;

import com.beta.pay.yeepay.request.DivideRequest;
import com.beta.pay.yeepay.response.BaseResponse;
import com.beta.pay.yeepay.utils.ZGTUtils;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 分账组件
 * Created by vector on 2016/11/30.
 */
public class Divide extends Component {

    private static final String API_URL = "https://o2o.yeepay.com/zgt-api/api/divide";

    private final Logger logger = LoggerFactory.getLogger(getClass());

    protected Divide(Yeepay yeepay) {
        super(yeepay);
    }

    @Override
    protected String getComponentName() {
        return "分账";
    }

    public BaseResponse divide(DivideRequest request) {
        Map<String, String> paramMap = toParamMap(request);
        Map<String, String> responseData = fetchData(API_URL, toParamMap(request),
                ZGTUtils.DIVIDEAPI_REQUEST_HMAC_ORDER, ZGTUtils.DIVIDEAPI_RESPONSE_HMAC_ORDER);
        return buildDivideResponse(responseData);
    }

    public Map<String, String> decodeApiResponse(String responseData) {
        return decodeData(responseData, ZGTUtils.DIVIDEAPICALLBACK_HMAC_ORDER);
    }

    private BaseResponse buildDivideResponse(Map<String, String> responseData) {
        BaseResponse response = new BaseResponse();
        response.setCustomerNumber(MapUtils.getString(responseData, "customernumber"));
        response.setRequestId(MapUtils.getString(responseData, "requestid"));
        response.setCode(MapUtils.getString(responseData, "code"));
        return response;
    }

    private Map<String, String> toParamMap(DivideRequest request) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("requestid", request.getRequestId());
        paramMap.put("orderrequestid", request.getOrderRequestId());
        paramMap.put("divideinfo", request.divideInfoString());
        paramMap.put("callbackurl", request.getCallbackUrl());
        return paramMap;
    }

}
